package com.eva.cms.biz.category;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eva.cms.biz.category.vo.CmsCategoryNodeVO;
import com.eva.dao.cms.model.CmsCategory;
import com.eva.service.cms.CmsCategoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Service
public class CmsCategoryBiz {

    @Resource
    private CmsCategoryService categoryService;

    /**
     * 查询栏目树
     *
     * @param withHidden 是否包含隐藏的栏目
     * @return List<CmsCategoryNode>
     */
    public List<CmsCategoryNodeVO> findTree(Boolean withHidden) {
        // 查询所有栏目
        QueryWrapper<CmsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(!withHidden, CmsCategory::getHidden, Boolean.FALSE)
                .eq(CmsCategory::getDeleted, Boolean.FALSE)
                .orderByAsc(CmsCategory::getSort);
        List<CmsCategory> categories = categoryService.findList(queryWrapper);
        // 转为树
        return categoryService.transferToTree(categories, CmsCategoryNodeVO.class);
    }

    /**
     * 查询子栏目树
     *
     * @param parentCategoryUid 父栏目UID
     * @return List<CmsCategoryNodeVO>
     */
    public List<CmsCategoryNodeVO> findSubTree (String parentCategoryUid, Boolean withHidden) {
        List<CmsCategoryNodeVO> nodes = this.findTree(withHidden);
        List<CmsCategoryNodeVO> subTree = this.findSubTree(parentCategoryUid, nodes);
        if (subTree == null) {
            return Collections.emptyList();
        }
        return subTree;
    }

    /**
     * 查找栏目树
     *
     * @param parentCategoryUid 父栏目UID
     * @param range 查找数据范围
     * @return List<CmsCategoryNodeVO>
     */
    private List<CmsCategoryNodeVO> findSubTree (String parentCategoryUid, List<CmsCategoryNodeVO> range) {
        for (CmsCategoryNodeVO node : range) {
            if (node.getUid().equals(parentCategoryUid)) {
                if (node.getChildren() != null) {
                    return (List<CmsCategoryNodeVO>) node.getChildren();
                }
                return Collections.emptyList();
            }
            if (node.getChildren() != null) {
                List<CmsCategoryNodeVO> children = this.findSubTree(parentCategoryUid, (List<CmsCategoryNodeVO>)node.getChildren());
                if (children != null) {
                    return children;
                }
            }
        }
        return null;
    }
}
